package cn.xawl.interview.thread;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author lh
 * @date 2020/08/25 21:57:13
 *
 * 写操作：原子的、独占的
 *
 * 读操作：共享操作
 * 1	开始写入：1
 * 2	开始写入：2
 * 2	写入完成
 * 3	开始写入：3
 * 1	写入完成
 * 3	写入完成
 * 1	开始读取
 * 2	开始读取
 * 1	读取完成：1
 * 2	读取完成：2
 * 3	开始读取
 * 3	读取完成：3
 *
 *
 **/
public class ReadWriteLockDemo {

    public static void main(String[] args) {
        Cache cache = new Cache();

        for (int i = 1; i <= 3; i++) {
            int finalI = i;
            new Thread(() -> {
                cache.put(finalI + "", finalI + "");
            }, String.valueOf(i)).start();
        }
        for (int i = 1; i <= 3; i++) {
            int finalI = i;
            new Thread(() -> {
                cache.get(finalI + "");
            }, String.valueOf(i)).start();
        }

    }

}


class Cache {
    private final Map<String, Object> cache = new HashMap<>();
//    private Lock lock = new ReentrantLock();
    private final ReadWriteLock lock = new ReentrantReadWriteLock();

    public void put(String k, Object v) {
        lock.writeLock().lock();
        try{
            System.out.println(Thread.currentThread().getName() + "\t开始写入：" + k);
            try {
                TimeUnit.MILLISECONDS.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            cache.put(k, v);
            System.out.println(Thread.currentThread().getName() + "\t写入完成");
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.writeLock().unlock();
        }

    }

    public Object get(String k) {
        lock.readLock().lock();

        try{
            System.out.println(Thread.currentThread().getName() + "\t开始读取");
            Object v = cache.get(k);
            System.out.println(Thread.currentThread().getName() + "\t读取完成：" + v);
            return v;
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.readLock().unlock();
        }
        return null;
    }

}